package no.cicero.testframework.xml.testcase;

import no.cicero.testframework.common.xml.XmlImporter;
import no.cicero.testframework.common.xml.XmlImporterDelegateBase;
import no.cicero.testframework.common.xml.XmlTag;
import no.cicero.testframework.model.testcase.ClientObject;
import no.cicero.testframework.model.testcase.Step;
import no.cicero.testframework.model.testcase.TestCase;
import no.cicero.testframework.xml.IXmlNameTable;
import org.xml.sax.SAXException;

public class StepImporter extends XmlImporterDelegateBase implements IXmlNameTable.IStepTag{
    private ClientObjectImporter clientObjectDelegate = null;

    private Step step = null;
    Step getStep() { return step; }

    private TestCase parent;
    public StepImporter(TestCase parent){
        this.parent = parent;
    }

    //----interface IXmlImporterDelegate
    @Override
    public void handleStartElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if( tag.getName().equalsIgnoreCase( ROOT_ELEMENT ) ) {
            step = new Step(parent);
        } else if(
            (
                tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT)
                && tag.getName().equalsIgnoreCase( ARGUMENTS_ELEMENT )
            ) || (
                tag.getParent().getName().equalsIgnoreCase(EXPECT_ELEMENT)
                && (
                    tag.getName().equalsIgnoreCase( EXPECTFAULT_ELEMENT )
                    || tag.getName().equalsIgnoreCase( EXPECTSUCCESS_ELEMENT )
                )
            )
        ) {
            clientObjectDelegate = new ClientObjectImporter();
            importer.pushDelegate(clientObjectDelegate);
        } else
            StepParametersImporterHelper.handleStartElement(importer, tag, step);
    }

    @Override
    public void handleEndElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if(clientObjectDelegate != null){
            ClientObject obj = clientObjectDelegate.getClientObject();
            if( tag.getName().equalsIgnoreCase(ARGUMENTS_ELEMENT) )
                step.setArguments(obj);
            else if( tag.getName().equalsIgnoreCase(EXPECTFAULT_ELEMENT) )
                step.setExpectedResult(false, obj);
            else if( tag.getName().equalsIgnoreCase(EXPECTSUCCESS_ELEMENT) )
                step.setExpectedResult(true, obj);
            
            clientObjectDelegate = null;
        }

    }

    @Override
    public void handleText(XmlImporter importer, XmlTag tag, String text) throws SAXException {
        if (tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT)) {
            StepParametersImporterHelper.handleText(importer, tag, text, step);
        }
    }

}
